<template>
	<div>
    <!-- 查看详情页 -->
    <el-breadcrumb separator="/">
      <!--面包屑 -->
      <el-breadcrumb-item :to="{ path: '/trialRecord' }">
        <i class="el-icon-s-home" style="margin-right: 15px; font-size: 16px"></i>试验记录
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <i  class="el-icon-menu" style="margin-right: 15px; font-size: 16px"></i>试验详情
      </el-breadcrumb-item>
    </el-breadcrumb>
		<div class="info">
      <div style="margin-bottom: 10px;height:40px">
        <el-button :disabled="review_status === null ? flags ? true : false : true"  @click="generatingRecord" style="float: right;" type="primary">生成记录</el-button>
      </div>
      <el-row>
        <el-col :span="6"><div class="grid-content bg-purple">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span class="span">{{station_name}}</span>
            </div>
            <el-carousel indicator-position="none" arrow="never" height="50px">
              <el-carousel-item v-for="(item, index) in data" :key="index">
                <div class="flex" v-for="(item1, index1) in item" :key="index1">
                <span>{{item1.instr_name}}</span>
                <span>{{item1.model}}</span>
            </div>
              </el-carousel-item>
            </el-carousel>
          </el-card>
          </div></el-col>
        <el-col :span="18"><div class="grid-content bg-purple-light">
          <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span  class="span">试验参数</span>
                <el-button style="float: right; padding: 3px 0" type="text" @click="allParameters">查看所有参数</el-button>
              </div>
              <el-row style="height: 50px; line-height: 50px; text-align: center;">
                <el-col :span="6">委试号：{{testNumber}}</el-col>
                <el-col :span="6">相对湿度(%RH)：{{RH}}</el-col>
                <el-col :span="6">大气压(kPa)：{{ATM}}</el-col>
                <el-col :span="6">温度(℃)：{{T}}</el-col>
              </el-row>
            </el-card>
          </div></el-col>
      </el-row>
      <el-card class="box-card main">
        <el-tabs v-model="activeName">
          
          <el-tab-pane v-for="(item,index) in datas" :key="index" :label="item.type" :name="item.type">
            <div  v-if="item.type === '辅助和控制回路的绝缘试验'">
              <el-button type="primary" :disabled="review_status === '1' ? true : false" v-if="flag" @click="edit" style="float: right; padding: 7px 20px; margin-bottom: 20px">编辑</el-button>
              <el-button type="primary" v-else @click="preservation"  style="float: right; padding: 7px 20px; margin-bottom: 20px">保存</el-button>
              <el-table :data="item.data" border style="width: 100%">
                <el-table-column prop="part" label="试验部位">
                </el-table-column>
                <el-table-column prop="jiaYa" label="加压部位">
                </el-table-column>
                <el-table-column prop="jieDi" label="接地部位">
                </el-table-column>
                <el-table-column prop="actuallyVolt" label="应施电压">
                </el-table-column>
                <el-table-column prop="testVolt" label="实测电压">
                  <template slot-scope="scope">
                    <!-- <el-form  v-if="!flag" :model="scope.row" :rules="rules" ref="ruleForm" label-width="0"> -->
                      <!-- <el-form-item label="" prop="testVolt"> -->
                        <el-input @change="change" v-if="!flag" v-model="scope.row['testVolt']" clearable></el-input>
                      <!-- </el-form-item> -->
                    <!-- </el-form> -->
                    <span v-else>{{scope.row['testVolt']}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="jiaYaCishu" label="加压次数">
                </el-table-column>
                <el-table-column prop="jiChuanCiShu" label="击穿次数">
                </el-table-column>
                <el-table-column prop="naiShouShiJian" label="耐受时间">
                </el-table-column>
              </el-table>
            </div>
            <div v-else>
               <el-table :data="item.data" border style="width: 100%">
                <el-table-column prop="product_area" label="防护面积" show-overflow-tooltip>
                  <template slot-scope="scope">
                   <span v-if="scope.row.product_area">{{scope.row.product_area}}</span>
                   <span v-else>--</span>
                  </template>
                </el-table-column>
                <el-table-column prop="product_height" label="防护高度" show-overflow-tooltip>
                  <template slot-scope="scope">
                   <span v-if="scope.row.product_height">{{scope.row.product_height}}</span>
                   <span v-else>--</span>
                  </template>
                </el-table-column>
                <el-table-column prop="product_length" label="防护长度" show-overflow-tooltip>
                  <template slot-scope="scope">
                   <span v-if="scope.row.product_length">{{scope.row.product_length}}</span>
                   <span v-else>--</span>
                  </template>
                </el-table-column>
                <el-table-column prop="product_width" label="防护宽度" show-overflow-tooltip>
                  <template slot-scope="scope">
                   <span v-if="scope.row.product_width">{{scope.row.product_width}}</span>
                   <span v-else>--</span>
                  </template>
                </el-table-column>
                <el-table-column prop="protect_level" label="防护等级" show-overflow-tooltip>
                  <template slot-scope="scope">
                   <span v-if="scope.row.protect_level">{{scope.row.protect_level}}</span>
                   <span v-else>--</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
		</div>
    <el-dialog
      title="生成记录"
      :visible.sync="dialogVisible"
      width="30%">
      <div style="display: flex; justify-content: center;">
        <el-radio v-model="radio" label="1">中文版</el-radio>
        <el-radio v-model="radio" label="2">中英版</el-radio>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="generatingRecords">确 定</el-button>
      </span>
    </el-dialog>
	</div>
</template>
<script>
// import eventBus from '../../public/eventBus'
import { serverURL, gkServerURL } from '../../public/setting'
export default {
	data() {
    const validateNameInput = (rule, value, callback) => {
      // console.log(value);
      const reg = /^[0-9.]*$/
      // console.log(reg.test(value));
      if (!reg.test(value)) {
        return callback(new Error('必须输入数字或小数点'))
      } else {
        callback()
      }
    }
    return{
      dialogVisible: false,
      radio: '1',
      rules: {
        'testVolt':[
            { validator: validateNameInput,  trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 4 到 6 个字符', trigger: 'blur' }
          ],
      },
      flag: true,
      datas: [],
      alarmCount: 0,
      beginTime: this.$route.query.beginTime,
      duration: this.$route.query.duration,
      instanceId: this.$route.query.instanceId,
      planName: this.$route.query.planName,
      testNumber: this.$route.query.testNumber,
      pk_ch_name: this.$route.query.pk_ch_name,
      tplt_name: this.$route.query.tplt_name,
      review_status: this.$route.query.review_status,
      testDate: this.$route.query.testDate,
      station_name: '',
      ATM: 0, // 大气压
      RH: 0, // 相对湿度
      T: 0, // 温度
      activeName: '',
      btnNo: 1,
      data: [],
      flags: false
    }
  },
	 methods: {
     generatingRecord() {
       let flag = false
       this.datas.forEach(item => {
         if(item.type === '辅助和控制回路的绝缘试验') {
           item.data.forEach(item1 => {
             if(item1.testVolt === '' || item1.testVolt === null) {
               flag = true
             }
           })
         }
       })
       if(flag) {
         return this.$message.error('请先填写辅助和控制回路的绝缘试验中实测电压值！')
       }
       this.dialogVisible = true
     },
     change(value) {
       const reg = /^[0-9.]*$/
       if (!reg.test(value)) {
        return this.$message.error('必须输入数字或小数点')
      }
     },
     allParameters() {
       this.$router.push({
         path: '/ShowAllParameterss',
         query: {
           instanceId: this.instanceId,
           testNumber: this.testNumber,
           pk_ch_name: this.pk_ch_name,
					 tplt_name: this.tplt_name,
           testDate: this.testDate,
           review_status: this.review_status
         }
       })
     },
      async getStationInfo() {
        const res = await this.$http.get(`/testRecordData/getStationInfo?instanceId=${this.instanceId}`)
        this.station_name = res.station_name
        this.data = res.result
      },
      async getTestTimeInfo () {
        const { result } = await this.$http.get(`/testRecordData/getTestTimeInfo?instanceId=${this.instanceId}`)
        this.beginTime = result.begin_time
        this.duration = result.duration
      },
      async getTestParam() {
        const { result } = await this.$http.get(`/testRecordData/getTestParam?instanceId=${this.instanceId}&testNumber=${this.testNumber}`)
        this.testNumber = result.testNumber
        this.ATM = result.ATM
        this.RH = result.RH
        this.T = result.T
      },
      async getTestData() {
        const { result } = await this.$http.get(`/testRecordData/getTestData?instanceId=${this.instanceId}`)
        let obj = {
          type: '其他',
          arr: ['试验部位','加压接地部位','标准阈值'],
          data: [
            {
              '试验部位': '活门',
              '加压接地部位': 'abc',
              '标准阈值': '1~4'
            }
          ]
        }
        // result.unshift(obj)
        this.datas = result
        let arrOne = []
        let arrTwo = []
        this.activeName = result[0].type
        result.forEach(item => {
          if(item.type === '雷电冲击耐受电压试验'){
            item.fenZha.forEach(item1 => {
              for(let i in item1){
                arrOne.push(Object.keys(item1).length)
              }
            })
            item.HeZha.forEach(item1 => {
              for(let i in item1){
                arrTwo.push(Object.keys(item1).length)
              }
            })
        }
      })
    },
    edit() {
      this.flag = false
    },
    reg (arrOne) {
      const reg = /^[0-9.]*$/
      let a
      for(let i = 0;i<arrOne.length; i++){
        console.log(arrOne[i].testVolt);
        if (!reg.test(arrOne[i].testVolt)) {
          a = 1
        } else if (arrOne[i].testVolt === '') {
          a = 2
        }
      }
      return a
    },
    async preservation() {
      console.log(123);
      let arrOne = []
      this.datas.forEach(item=>{
        if(item.type === '辅助和控制回路的绝缘试验'){
          item.data.forEach((item1,index) => {
            arrOne[index] = {dielId: item1.dielId,testVolt: item1.testVolt}
          })
        }
      })
      let x = await this.reg(arrOne)
      if(x === 1) {
        return this.$message.error('必须输入数字或小数点，并且只保留小数点后两位')
      } else if (x === 2) {
        return this.$message.error('不允许为空')
      }
      arrOne.forEach(async (item) => {
        console.log(item);
        await this.$http.post('/testRecordData/editOtherTest',{dielId: item.dielId,testVolt: item.testVolt})
      })
      this.flag = true

    },
    async getAlarmCount() {
      const { result } = await this.$http.get(`/testRecordData/getAlarmCount?instanceId=${this.instanceId}`).catch(err=>err)
      this.alarmCount = result
    },
    async generatingRecords() {
        if(this.radio === '2') {
          const loading = this.$loading({
          lock: true,
          text: '记录生成中请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
          });
          try {
            const ret = await this.$http.get(`${serverURL}/trialRecord/sendPicture?instanceId=${this.instanceId}`)
            console.log(ret);
            const res = await this.$http.get(`${gkServerURL}/trialRecord/ifCreatRecord?instanceId=${this.instanceId}&type=en&testNumber=${this.testNumber}&testDate=${this.testDate.split(' ')[0]}&fileType=记录`)
            if(res.code !== 200){
              loading.close();
              // this.$message.error('生成失败，请稍后重试')
            } else {
              this.flags = true
              loading.close();
              this.$message.success('生成成功！')
              this.dialogVisible = false
            } 
          } catch(err) {
            loading.close();
            // this.$message.error('生成失败，请稍后重试')
          } 
          }else if (this.radio === '1'){ // 中文版
            const loading = this.$loading({
            lock: true,
            text: '记录生成中请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
            });
            try {
              const ret = await this.$http.get(`${serverURL}/trialRecord/sendPicture?instanceId=${this.instanceId}`)
              console.log(ret);
              const res = await this.$http.get(`${gkServerURL}/trialRecord/ifCreatRecord?instanceId=${this.instanceId}&type=cn&testNumber=${this.testNumber}&testDate=${this.testDate.split(' ')[0]}&fileType=记录`)
              if(res.code !== 200){
                loading.close();
                // this.$message.error('生成失败，请稍后重试')
              } else {
                this.flags = true
                loading.close();
                this.$message.success('生成成功！')
                this.dialogVisible = false
              }
            } catch(err) {
              console.log(err);
              loading.close();
              // this.$message.error('生成失败，请稍后重试')
            }
          }
      }
    },
    created() {
      // 试验的工位及设备信息
      this.getStationInfo()
      // 获得试验时间信息
      this.getTestTimeInfo()
      //获得试验的部分参数
      this.getAlarmCount()
      this.getTestParam()
      this.getTestData()
    },
    mounted() {
      // eventBus.$emit('getHeight')
    }
};
</script>
<style lang="scss" scoped>
@import "./TestRecordData.scss";
</style>